<template>
	<div class="sales-invoice-edit">
		<el-card shadow="never">
			<template #header>
				<div class="card-header">
					<span>编辑销项发票</span>
					<div class="header-actions">
						<el-button type="primary" :loading="submitting" @click="onSubmit">保存</el-button>
						<el-button text type="info" @click="goBack">返回</el-button>
					</div>
				</div>
			</template>

			<el-skeleton v-if="loading" :rows="10" animated />
			<template v-else>
				<el-form ref="formRef" :model="form" :rules="rules" label-width="110px" status-icon>
					<el-row :gutter="16">
						<el-col :span="8">
							<el-form-item label="发票号码" prop="invoiceNo">
								<el-input v-model="form.invoiceNo" placeholder="请输入发票号码" clearable />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="订单ID" prop="orderId">
								<el-select v-model="form.orderId" placeholder="请选择订单" style="width: 100%" filterable>
									<el-option v-for="item in orderList" :key="item.id || item.orderId"
										:label="item.dingDanBianHao || item.orderNo"
										:value="Number(item.id || item.orderId)" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="客户" prop="customerId">
								<el-select v-model="form.customerId" placeholder="请选择客户" style="width: 100%" filterable>
									<el-option v-for="item in customerList" :key="item.customerID || item.id"
										:label="item.customername || item.customerName"
										:value="Number(item.customerID || item.id)" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="发票日期" prop="invoiceDate">
								<el-date-picker v-model="form.invoiceDate" type="date" placeholder="选择日期" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="发票类型" prop="invoiceType">
								<el-select v-model="form.invoiceType" style="width: 100%">
									<el-option value="普通" label="普通" />
									<el-option value="专用" label="专用" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="状态" prop="invoiceStatus">
								<el-select v-model="form.invoiceStatus" style="width: 100%">
									<el-option :value="0" label="待开具" />
									<el-option :value="1" label="已开具" />
									<el-option :value="2" label="已作废" />
									<el-option :value="3" label="已红冲" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="税率(%)" prop="taxRate">
								<el-input-number v-model="form.taxRate" :min="0" :max="100" :step="1" />
							</el-form-item>
						</el-col>
						<el-col :span="16">
							<el-form-item label="备注" prop="remarks">
								<el-input v-model="form.remarks" placeholder="备注(可选)" clearable type="textarea"
									:rows="2" />
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>

				<el-divider>发票明细</el-divider>
				<div class="table-actions">
					<el-button type="primary" plain @click="addItem">新增一行</el-button>
				</div>
				<el-table :data="form.invoiceDetails" border size="small" style="width: 100%">
					<el-table-column type="index" label="#" width="50" />
					<el-table-column label="产品名称" min-width="180">
						<template #default="{ row }">
							<el-input v-model="row.productName" placeholder="产品名称" clearable />
						</template>
					</el-table-column>
					<el-table-column label="规格" min-width="140">
						<template #default="{ row }">
							<el-input v-model="row.specification" placeholder="规格" clearable />
						</template>
					</el-table-column>
					<el-table-column label="单位" width="120">
						<template #default="{ row }">
							<el-input v-model="row.unit" placeholder="单位" clearable />
						</template>
					</el-table-column>
					<el-table-column label="数量" width="130" align="right">
						<template #default="{ row }">
							<el-input-number v-model="row.quantity" :min="1" :step="1" controls-position="right" />
						</template>
					</el-table-column>
					<el-table-column label="单价(不含税)" width="160" align="right">
						<template #default="{ row }">
							<el-input-number v-model="row.unitPrice" :min="0" :step="0.01" :precision="2"
								controls-position="right" />
						</template>
					</el-table-column>
					<el-table-column label="税率(%)" width="130" align="right">
						<template #default="{ row }">
							<el-input-number v-model="row.taxRate" :min="0" :max="100" :step="1" />
						</template>
					</el-table-column>
					<el-table-column label="税额" width="140" align="right">
						<template #default="{ row }">{{ formatMoney(row.taxAmount) }}</template>
					</el-table-column>
					<el-table-column label="小计(含税)" width="160" align="right">
						<template #default="{ row }">{{ formatMoney(row.subtotalAmount) }}</template>
					</el-table-column>
					<el-table-column label="行备注" min-width="160">
						<template #default="{ row }">
							<el-input v-model="row.remarks" placeholder="备注" clearable />
						</template>
					</el-table-column>
					<el-table-column label="操作" width="100" align="center">
						<template #default="{ $index }">
							<el-button type="danger" text @click="removeItem($index)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>

				<div class="summary">
					<div class="summary-item">
						<span>合计(不含税)：</span>
						<b>{{ formatMoney(subtotalAmount) }}</b>
					</div>
					<div class="summary-item">
						<span>税额：</span>
						<b>{{ formatMoney(taxAmount) }}</b>
					</div>
					<div class="summary-item">
						<span>发票金额(含税)：</span>
						<b class="total">{{ formatMoney(invoiceAmount) }}</b>
					</div>
				</div>
			</template>
		</el-card>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref, computed, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { APIs } from '@/Http/http'
import { useCounterStore } from '@/stores/counter'

type InvoiceDetail = {
	detailId: number | null
	productName: string
	specification: string
	unit: string
	quantity: number
	unitPrice: number
	amount: number
	taxRate: number
	taxAmount: number
	subtotalAmount: number
	remarks: string
	isDelete: boolean
}

type SalesInvoiceForm = {
	invoiceId: number
	invoiceNo: string
	orderId: number | null
	customerId: number | null
	invoiceAmount: number
	invoiceDate: string | Date
	invoiceType: string
	invoiceStatus: number
	taxRate: number
	taxAmount: number
	subtotalAmount: number
	remarks: string
	updateName: string
	invoiceDetails: InvoiceDetail[]
}

const route = useRoute()
const router = useRouter()
const store = useCounterStore()

const id = Number(route.params.id)
const loading = ref(false)
const submitting = ref(false)
const formRef = ref()

// 订单列表数据
const orderList = ref<any[]>([])

// 客户列表数据
const customerList = ref<any[]>([])

const form = reactive<SalesInvoiceForm>({
	invoiceId: id,
	invoiceNo: '',
	orderId: null as number | null,
	customerId: null as number | null,
	invoiceAmount: 0,
	invoiceDate: '',
	invoiceType: '',
	invoiceStatus: 0,
	taxRate: 13,
	taxAmount: 0,
	subtotalAmount: 0,
	remarks: '',
	updateName: store?.Users?.userNickname || '',
	invoiceDetails: [
		{ detailId: null, productName: '', specification: '', unit: '', quantity: 1, unitPrice: 0, amount: 0, taxRate: 13, taxAmount: 0, subtotalAmount: 0, remarks: '', isDelete: false }
	]
})

const rules = reactive({})

const subtotalAmount = computed(() => {
	return form.invoiceDetails.reduce((sum, it) => sum + (Number(it.quantity) * Number(it.unitPrice) || 0), 0)
})
const taxAmount = computed(() => {
	return Number((form.invoiceDetails.reduce((sum, it) => sum + (Number(it.quantity) * Number(it.unitPrice) * (Number(it.taxRate) / 100) || 0), 0)).toFixed(2))
})
const invoiceAmount = computed(() => Number((subtotalAmount.value + taxAmount.value).toFixed(2)))

watch(
	() => form.invoiceDetails.map(i => [i.quantity, i.unitPrice, i.taxRate]),
	() => {
		form.invoiceDetails.forEach(i => {
			i.amount = Number((Number(i.quantity) * Number(i.unitPrice)).toFixed(2))
			i.taxAmount = Number((Number(i.quantity) * Number(i.unitPrice) * (Number(i.taxRate) / 100)).toFixed(2))
			i.subtotalAmount = Number((i.amount + i.taxAmount).toFixed(2))
		})
		form.subtotalAmount = Number(subtotalAmount.value.toFixed(2))
		form.taxAmount = Number(taxAmount.value.toFixed(2))
		form.invoiceAmount = Number(invoiceAmount.value.toFixed(2))
	},
	{ deep: true }
)

function addItem() {
	form.invoiceDetails.push({ detailId: null, productName: '', specification: '', unit: '', quantity: 1, unitPrice: 0, amount: 0, taxRate: form.taxRate, taxAmount: 0, subtotalAmount: 0, remarks: '', isDelete: false })
}

function removeItem(index: number) {
	form.invoiceDetails.splice(index, 1)
}

function formatMoney(v: number | string) {
	const n = Number(v || 0)
	return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

function goBack() {
	router.back()
}

/**
 * 加载订单列表数据
 */
async function loadOrderList() {
	try {
		// 调用订单列表接口
		const res = await APIs.get('/api/SalesInvoice/DingdanQuery')

		// 处理响应数据
		if (res && res.status === 200 && res.data && res.data.code === 100) {
			orderList.value = res.data.data || []
		} else {
			ElMessage.error('获取订单列表失败')
		}
	} catch (e: any) {
		ElMessage.error(e?.response?.data?.message || '请求失败')
	}
}

/**
 * 加载客户列表数据
 */
async function loadCustomerList() {
	try {
		// 调用客户列表接口
		const res = await APIs.get('/api/SalesInvoice/clietQuery')

		// 处理响应数据
		if (res && res.status === 200 && res.data && res.data.code === 100) {
			customerList.value = res.data.data || []
		} else {
			ElMessage.error('获取客户列表失败')
		}
	} catch (e: any) {
		ElMessage.error(e?.response?.data?.message || '请求失败')
	}
}

/**
 * 加载发票详情数据
 */
async function loadDetail() {
	try {
		loading.value = true
		// 详情接口参数按 invoiceId 传递，兼容 id
		const res = await APIs.get('/api/SalesInvoice/GetSalesInvoiceDetail', { params: { invoiceId: id, id } })
		const data = res?.data?.data || res?.data || {}

		// 确保所有字段正确反填，处理可能的空值和类型转换问题
		form.invoiceId = data.invoiceId !== undefined && data.invoiceId !== null ? Number(data.invoiceId) : id
		form.invoiceNo = data.invoiceNo !== undefined ? String(data.invoiceNo) : ''
		// 特别处理orderId，根据JSON数据格式，0表示未选择订单
		form.orderId = data.orderId !== undefined && data.orderId !== null && Number(data.orderId) !== 0 ? Number(data.orderId) : null
		// 处理customerId，确保是有效的数字
		form.customerId = data.customerId !== undefined && data.customerId !== null ? Number(data.customerId) : null
		form.invoiceAmount = data.invoiceAmount !== undefined ? Number(data.invoiceAmount) : 0
		form.invoiceDate = data.invoiceDate !== undefined ? data.invoiceDate : ''
		form.invoiceType = data.invoiceType !== undefined ? String(data.invoiceType) : ''
		form.invoiceStatus = data.invoiceStatus !== undefined ? Number(data.invoiceStatus) : 0
		form.taxRate = data.taxRate !== undefined && data.taxRate !== null ? Number(data.taxRate) : form.taxRate
		form.taxAmount = data.taxAmount !== undefined ? Number(data.taxAmount) : 0
		form.subtotalAmount = data.subtotalAmount !== undefined ? Number(data.subtotalAmount) : 0
		form.remarks = data.remarks !== undefined ? String(data.remarks) : ''
		form.updateName = store?.Users?.userNickname || form.updateName

		// 处理发票明细
		const detailsSrc = data.invoiceDetails || data.details || []
		form.invoiceDetails = (Array.isArray(detailsSrc) ? detailsSrc : []).map((i: any) => ({
			detailId: i.detailId !== undefined && i.detailId !== null ? i.detailId : (i.id !== undefined && i.id !== null ? i.id : null),
			productName: i.productName !== undefined ? String(i.productName) : '',
			// 同时兼容specification和specifications字段，根据JSON数据格式使用specifications优先
			specification: i.specifications !== undefined ? String(i.specifications) : (i.specification !== undefined ? String(i.specification) : ''),
			unit: i.unit !== undefined ? String(i.unit) : '',
			quantity: i.quantity !== undefined && i.quantity !== null ? Number(i.quantity) : 1,
			unitPrice: i.unitPrice !== undefined && i.unitPrice !== null ? Number(i.unitPrice) : 0,
			amount: i.amount !== undefined && i.amount !== null ? Number(i.amount) : 0,
			taxRate: i.taxRate !== undefined && i.taxRate !== null ? Number(i.taxRate) : form.taxRate,
			taxAmount: i.taxAmount !== undefined && i.taxAmount !== null ? Number(i.taxAmount) : 0,
			subtotalAmount: i.subtotalAmount !== undefined && i.subtotalAmount !== null ? Number(i.subtotalAmount) : 0,
			remarks: i.remarks !== undefined ? String(i.remarks) : '',
			isDelete: i.isDelete !== undefined ? Boolean(i.isDelete) : false
		}))

		// 确保至少有一条明细记录
		if (!form.invoiceDetails.length) {
			form.invoiceDetails = [{ detailId: null, productName: '', specification: '', unit: '', quantity: 1, unitPrice: 0, amount: 0, taxRate: form.taxRate, taxAmount: 0, subtotalAmount: 0, remarks: '', isDelete: false }]
		}
	} catch (e: any) {
		ElMessage.error(e?.response?.data?.message || '加载详情失败')
	} finally {
		loading.value = false
	}
}

async function onSubmit() {
	try {
		submitting.value = true
		const payload = {
			invoiceId: Number(form.invoiceId),
			invoiceNo: form.invoiceNo,
			orderId: Number(form.orderId || 0),
			customerId: Number(form.customerId || 0),
			invoiceAmount: Number(invoiceAmount.value || 0),
			invoiceDate: form.invoiceDate ? new Date(form.invoiceDate as any).toISOString() : new Date().toISOString(),
			invoiceType: form.invoiceType || '普通',
			invoiceStatus: Number(form.invoiceStatus || 0),
			taxRate: Number(form.taxRate || 0),
			taxAmount: Number(taxAmount.value || 0),
			subtotalAmount: Number(subtotalAmount.value || 0),
			remarks: form.remarks || '',
			updateName: store?.Users?.userNickname || form.updateName || '',
			invoiceDetails: form.invoiceDetails.map(i => ({
				detailId: i.detailId ?? 0,
				productName: i.productName,
				specification: i.specification,
				unit: i.unit,
				quantity: Number(i.quantity) || 0,
				unitPrice: Number(i.unitPrice) || 0,
				amount: Number(i.amount) || 0,
				taxRate: Number(i.taxRate) || 0,
				taxAmount: Number(i.taxAmount) || 0,
				subtotalAmount: Number(i.subtotalAmount) || 0,
				remarks: i.remarks || '',
				isDelete: Boolean(i.isDelete || false)
			}))
		}
		const res = await APIs.put('/api/SalesInvoice/UpdateSalesInvoice', payload)
		if (res && (res.status === 200 || res.status === 201)) {
			ElMessage.success('保存成功')
			router.back()
		} else {
			ElMessage.error('保存失败')
		}
	} catch (e: any) {
		ElMessage.error(e?.response?.data?.message || '请求失败')
	} finally {
		submitting.value = false
	}
}

onMounted(async () => {
	// 确保订单和客户列表数据完全加载后再加载发票详情
	await Promise.all([loadOrderList(), loadCustomerList()])
	await loadDetail()
})
</script>

<style scoped>
.sales-invoice-edit {
	padding: 12px;
}

.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.header-actions {
	display: flex;
	gap: 8px;
}

.table-actions {
	margin-bottom: 8px;
}

.summary {
	margin-top: 12px;
	display: flex;
	gap: 24px;
	justify-content: flex-end;
}

.summary-item span {
	color: var(--el-text-color-regular);
	margin-right: 8px;
}

.summary-item .total {
	color: var(--el-color-primary);
}
</style>
